package com.tools;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringReader;
import java.util.Date;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import com.data.DataBase;
import com.entity.ManagerPerson;

/**
 * 初始化的类
 * 
 * @author Administrator
 *
 */
public class StuInit {

	
	/**
	 * 启动的时候初始化数据
	 */
	public static void start() {
		FileReader fileReader = null;
		File file = new File(StuInit.class.getProtectionDomain().getCodeSource().getLocation().getPath() + "StuManagerConfig.ini");

		if (file.exists()) {
			// 配置文件存在，读取
			System.out.println("正在读取数据...");
			DataBase base=null;
			if(file.exists()){
				try {
					fileReader=new FileReader(file);
				
					int temp;
					
					StringBuffer buffer=new StringBuffer();
					
					while((temp=fileReader.read())!=-1){
						buffer.append((char)temp);
					}
					
					JAXBContext context = JAXBContext.newInstance(DataBase.class);  
		            Unmarshaller unmarshaller = context.createUnmarshaller();  
				
		            base = (DataBase)unmarshaller.unmarshal(new StringReader(buffer.toString())); 
				} catch (Exception e) {
					e.printStackTrace();
				}
				finally {
					try {
						fileReader.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}



		} else {
			// 不存在，初始化管理员
			ManagerPerson person = new ManagerPerson();
			person.setUsername("admin");
			person.setPassword("admin");
			person.setName("张三");
			person.setCreateDate(new Date());
			person.setSex(1);
			person.setAge(20);
			person.setRank(0);
			person.setAddress("陕西省1");
			DataBase.getManagerPersons().put(person.getUsername(), person);
		}
	}

	/**
	 * 程序结束的时候保存数据
	 */
	public static void stop() {
		FileWriter fileWriter = null;
		BufferedWriter bufferedWriter = null;
		File file = new File(StuInit.class.getProtectionDomain().getCodeSource().getLocation().getPath() + "StuManagerConfig.ini");

		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				System.out.println("配置文件保存失败");
				e.printStackTrace();
			}
		}
		
		DataBase base=new DataBase();

		try {
			fileWriter = new FileWriter(file);
			bufferedWriter = new BufferedWriter(fileWriter);

			JAXBContext context=JAXBContext.newInstance(DataBase.class);
			Marshaller marshaller=context.createMarshaller();
			marshaller.marshal(base,fileWriter);

		} catch (Exception e) {
			System.out.println("数据保存失败，可能出现异常");
			e.printStackTrace();
		} finally {
			try {
				bufferedWriter.close();
				fileWriter.close();
			} catch (IOException e) {
				System.out.println("数据保存出现异常，数据可能损坏");
				e.printStackTrace();
			}

		}

	}

	

}
